﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NC.Infrastructure.Cache;
using NC.Infrastructure.Data;

namespace NC.Service.MemoryCache
{
    public class MemoryCacheService:IMemoryCacheService
    {

        private const string accessToken = "accessToken";
        private readonly IRepository<Cather.Target> _targetRepository;

        public MemoryCacheService(IRepository<Cather.Target> targetRepository)
        {
            this._targetRepository = targetRepository;
        }


        /// <summary>
        /// 根据AppId来获取相应AccessTokenId
        /// </summary>
        /// <param name="appId">用户每个网站所携带的AppId</param>
        /// <returns>返回AccessToken</returns>
        public string GetAccessTokenByAppId(string appId)
        {
            var entity = _targetRepository.Get(n => n.AppId == appId).FirstOrDefault();
            if (entity==null||string.IsNullOrEmpty(entity.AppId))
                throw new Exception("不存在此AppId");
            string token = Guid.NewGuid().ToString();
            CacheManager.GetCacher(token).Set(token, entity.Id);
            return token;
        }

        /// <summary>
        /// 检查此token是否存在
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public bool CheckAccessTokenExsit(string token)
        {
            return CacheManager.GetCacher(accessToken).Get(token) == null;
        }
    }
}
